﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sexybeauty.Core.Biz.HM.Impl;
using System.Web;
using System.Timers;
using Sexybeauty.Framework.Common;

namespace Sexybeauty.Core.Biz.HM
{
    public static class HitManager
    {
        private static Dictionary<HitType, Dictionary<string, IHitModify>> data = null;
        private static Timer timer = null;
        private static object sync_key = new object();
        static HitManager()
        {
            data = new Dictionary<HitType, Dictionary<string, IHitModify>>();
            timer = new Timer();
            timer.Interval = 10 * 60 * 1000;
            timer.Enabled = true;
            timer.Elapsed += (o, e) => { Persistence(); };
            timer.Start();

        }
        private static IHitModify BuildHandle(HitType type)
        {
            switch (type)
            { 
                case HitType.MemberCount:
                    return new Sexybeauty.Core.Biz.HM.Impl.UserPopularity() as IHitModify;
                default:
                    return null;
            }
        }
        public static void Modify(HitType type, string id, object ctx)
        {
            if (!data.Keys.Any(c => c == type))
            {
                lock (sync_key)
                {
                    data.Add(type, new Dictionary<string, IHitModify>() { 
                        { id, BuildHandle(type) } 
                    });
                }
            }
            else
            {
                if (!data[type].Any(c => c.Key == id))
                {
                    lock (sync_key)
                    {
                        data[type].Add(id, BuildHandle(type));
                    }
                }
                else
                {
                    data[type][id].DoModify(ctx);
                }
            }
        }
        public static void Persistence()
        {
            try
            {
                System.Threading.Monitor.Enter(data);
                Dictionary<HitType, Dictionary<string, IHitModify>> copy = new Dictionary<HitType, Dictionary<string, IHitModify>>(data);
                data.Clear();
                System.Threading.Monitor.Exit(data);
                foreach (var cell in copy)
                {
                    foreach (var workcell in cell.Value)
                    {
                        workcell.Value.DoPersistence(workcell.Key);
                    }
                }
                copy.Clear();
            }
            catch (Exception e)
            {
                LogHelper.Write(CommonLogger.System, LogLevel.Error, e);
            }
        }
    }
}
